package notice

import (
	"fmt"
	"httpadmin/go-attribute/application/core"
	"httpadmin/go-attribute/service/notice/common"
	"httpadmin/go-attribute/service/notice/data"

	"github.com/gin-gonic/gin"
)

type HandlerMaker func() IHandler

var handlerMakerMap = make(map[string]HandlerMaker, 10)

// 注册 IHandler
// 用个 maker 是为了每次new一个对象
func RegisterNoticeHandlerMaker(mediaId string, maker HandlerMaker) {
	handlerMakerMap[mediaId] = maker
}

// 选择是哪个媒体的 handler 来处理notice
func selectHandler(c *gin.Context) IHandler {
	mediaId := c.Query("mediaId")
	if mediaId != "" {
		maker := handlerMakerMap[mediaId]
		if maker != nil {
			return maker()
		}
	}
	return nil
}

type IHandler interface {
	// 提取检测链接里的设备信息
	ExtractDeviceInfo(*gin.Context) (data.IDevice, error)
	// 提取 callback 信息
	ExtractCallbackInfo(*gin.Context) data.ICallback
	// 保存用于归因的字段
	SaveAttributeMark(data.IDevice) error
	// 要返还给媒体的数据
	SetReturnData(*core.Wrap)
}

type HandlerDto struct {
	IHandler
}

func (h *HandlerDto) ExtractDeviceInfo(ctx *gin.Context) (data.IDevice, error) {
	return common.ExtractNoticeData(ctx)
}

// 根据设备标识保存 feedback 信息
func (h *HandlerDto) SaveAttributeMark(device data.IDevice) error {
	marks := device.GetDeviceMarks()
	// todo redis pipeline save all (key shard)
	fmt.Println(marks)
	return nil
}

func (h *HandlerDto) SetReturnData(app *core.Wrap) {
	app.StringOut("ok")
}
